package com.lv.suyiyong.hfr.ui

import android.Manifest
import android.app.Dialog
import android.content.Intent
import android.content.res.Configuration
import android.net.Uri
import android.os.Build
import android.text.TextUtils
import android.view.Gravity
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import androidx.activity.viewModels
import androidx.annotation.RequiresApi
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.azhon.appupdate.listener.OnDownloadListener
import com.azhon.appupdate.manager.DownloadManager
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.DeviceUtils
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SPStaticUtils
import com.google.gson.reflect.TypeToken
import com.jeremyliao.liveeventbus.LiveEventBus
import com.lv.common.base.BaseActivity
import com.lv.common.base.BaseApplication
import com.lv.common.bean.CustomMessageBean
import com.lv.common.dialog.TipsCancel2Dialog
import com.lv.common.event.VersionUpdataRefreshEvent
import com.lv.common.im.GenerateTestUserSig
import com.lv.common.im.MemoryCallBack
import com.lv.common.im.push.OfflineMessageDispatcher
import com.lv.common.imp.OnDialogListener
import com.lv.common.network.model.DataResult
import com.lv.common.service.UpdataAppService
import com.lv.common.thirdparty.ShareUtils
import com.lv.common.utils.ARoutUtils
import com.lv.common.utils.Constants
import com.lv.common.utils.LocationUtils
import com.lv.common.utils.LogUtil
import com.lv.common.utils.MyUtils
import com.lv.common.utils.PermissionXUtils
import com.lv.common.utils.PermissionXUtilsCallback
import com.lv.common.utils.YgxUtilsKt
import com.lv.common.utils.showToast
import com.lv.service.bean.FindProsBean
import com.lv.service.bean.ScanCodeBean
import com.lv.service.dialog.FirstDialog
import com.lv.service.event.HomeTabEvent
import com.lv.service.event.LocationChangeEvent
import com.lv.service.event.LocationEvent
import com.lv.service.event.MessageCirCountEvent
import com.lv.service.event.MessageCountEvent
import com.lv.service.event.PlayStatus
import com.lv.service.event.RefreshPageEvent
import com.lv.service.event.VideoPlayEvent
import com.lv.service.model.EditorViewModel
import com.lv.service.model.ServiceViewModel
import com.lv.service.net.ADStatisticsReqBody
import com.lv.service.network.BaseYgxRsp
import com.lv.service.network.onBizError
import com.lv.service.network.onBizOK
import com.lv.service.network.onFailure
import com.lv.service.network.onSuccess
import com.lv.service.repo.UserDbHelper
import com.lv.service.repo.UserInfo
import com.lv.service.room.address.AddressCurrentDbHelper
import com.lv.service.room.address.CurrentAddress
import com.lv.service.room.category.CategoryBean
import com.lv.service.utils.YgxAroutPageKt
import com.lv.service.utils.YgxRoomToolsKt
import com.lv.service.utils.YgxToolsKt
import com.lv.service.weidget.canlender.DateAndTimeUtil
import com.lv.suyiyong.hfr.R
import com.lv.suyiyong.hfr.YgxApplication
import com.lv.suyiyong.hfr.bean.TokenBean
import com.lv.suyiyong.hfr.bean.VersionListBean
import com.lv.suyiyong.hfr.bean.VersionUpdate
import com.lv.suyiyong.hfr.databinding.ActivityHomeBinding
import com.lv.suyiyong.hfr.dialog.VersionUpdateDialog
import com.lv.suyiyong.hfr.moudel.MainPageViewModel
import com.lv.suyiyong.hfr.moudel.MainViewModel
import com.lv.suyiyong.hfr.widget.HomeBottomTabNewWidget
import com.lv.suyiyong.hfr.widget.HomeBottomTabWidget
import com.tencent.imsdk.v2.V2TIMConversation
import com.tencent.imsdk.v2.V2TIMConversationListFilter
import com.tencent.imsdk.v2.V2TIMConversationListener
import com.tencent.imsdk.v2.V2TIMConversationResult
import com.tencent.imsdk.v2.V2TIMManager
import com.tencent.imsdk.v2.V2TIMValueCallback
import com.tencent.qcloud.tuicore.TUILogin
import com.tencent.qcloud.tuicore.interfaces.TUICallback
import com.tencent.qcloud.tuicore.util.SPUtils
import com.tencent.qcloud.tuikit.tuiconversation.bean.ConversationInfo
import com.tencent.qcloud.tuikit.tuiconversation.commonutil.ConversationUtils
import com.ygx.zxing.utils.CodeUtils
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.koin.androidx.viewmodel.ext.android.viewModel
import java.io.File
import java.net.URLDecoder
import kotlin.system.exitProcess


@Route(path = ARoutUtils.HomeActivityURL)
class HomeActivity : BaseActivity<ActivityHomeBinding>() {
    @Autowired(name = "tabId")
    @JvmField
    var mTab = 0
    private var addressDefult = CurrentAddress(
        0, "420000", "湖北省", "武汉市", "汉阳区",
        System.currentTimeMillis(), "30.55702", "114.21101"
    )

    private val LOCATION_TIME = 60 * 60 * 1000

    //    private val LOCATION_TIME = 1 * 10 * 1000
    private var mLocationDialog: TipsCancel2Dialog? = null

    private var loadAddress = false//是否定位过
    private var BOTTOM_TAB_POSITION = 0
    private var mCirNum = 0
    private var mMessageNum = 0
    private var isLogin = false
    private var mUserId = ""

    //    private var mVersionListBean: VersionUpdate? = null
    private val mEditorViewModel by viewModels<EditorViewModel>()

    //    private var mCurrentProvince = ""//当前展示的省份
    private var mUserInfo: UserInfo? = null
    private val uiConvList = mutableListOf<V2TIMConversation>()
    private val mAddressBeans = mutableListOf<CategoryBean>()
    private var ID_MySelf = ""

    //    private var mCopyText = ""//外部复制的内容
    private var mUserTxaccid = ""
    private val pageViewModel by viewModels<MainPageViewModel>()
    private val viewModel: MainViewModel by viewModel()
    private val viewModelService: ServiceViewModel by viewModel()
    private lateinit var upDataDialog: VersionUpdateDialog
    private lateinit var downUrl: String
    private val myScope: CoroutineScope = CoroutineScope(SupervisorJob())
    private var mNewYear = 0
    override fun getLayoutRes() = R.layout.activity_home
    override fun initView() {
        super.initView()
        startLoading()
        ARouter.getInstance().inject(this)
        //新年主题展示时间：1月22号-2月12号
        val dateOneBigger: Boolean = DateAndTimeUtil.isInsideRange("2025-01-22", "2025-02-12")
        if (dateOneBigger) {
            mNewYear = 1
        } else {
            mNewYear = 0
        }
        SPStaticUtils.put(Constants.NEWYEAR, mNewYear)
        initTabStyle()
        YgxRoomToolsKt.doWorkManager(this)
    }

    private fun loadUI() {

        lifecycleScope.launchWhenCreated {
//            val taskFindBanner = async { findAllBanner() }
//            val taskFindVersionUpdate = async {
//                val versionResult = findVersionUpdate()
//                parseFindVersionUpdateResult(versionResult)
//            }
            val taskFindPros = async {
                val findProsResult = findProsSuspend()
                parseFindProsResult(findProsResult)
            }
//            taskFindVersionUpdate.await()
            taskFindPros.await()

            val taskADStatistics = async {
                saveAdStatistics()//广告统计
            }
//            val taskCheckToken = async {
//                val tokenResult = checkTokenSuspend()
//                parseTokenResult(tokenResult)
//            }
            loadFinished()
        }
    }

    private suspend fun findProsSuspend(): DataResult<BaseYgxRsp> {
        val mProsMap = mutableMapOf<String, String>(
            "address" to "1",
            "category" to "1",
            "spuCategory" to "1",
        )
        return withContext(Dispatchers.IO) {
            myScope.async {
                viewModelService.findPros(mProsMap)
            }.await()
        }
    }


    private fun parseFindProsResult(data: DataResult<BaseYgxRsp>) {
        data.onSuccess {
            onBizOK<FindProsBean> { code, data, message, result ->
                data?.let {
                    lifecycleScope.launch {
                        //商品分类信息
                        this.launch {
                            val categorys = it.category
                            if (categorys != null) {
                                YgxRoomToolsKt.saveRoomCategory(this@HomeActivity, categorys)
                                mEditorViewModel.liveCategoryData.postValue(categorys)
                            }
                        }
                        this.launch {
                            val address = it.address
                            if (address != null) {
                                YgxRoomToolsKt.saveAddressRoom(this@HomeActivity, address)
                            }
                        }
                        this.launch {
                            val categoryList = it.spuCategory
                            if (categoryList != null) {
                                YgxRoomToolsKt.saveGoodsCategory(this@HomeActivity, categoryList)
                                mEditorViewModel.liveSpuCategoryData.postValue(categoryList)
                            }
                        }
                    }

                }
                onBizError<FindProsBean> { code, message, data ->
                    showToast(message)
                }
            }
        }
        data.onFailure {
            LogUtils.e("eee")
        }
    }


    private suspend fun findVersionUpdate(): DataResult<BaseYgxRsp> {
        return withContext(Dispatchers.IO) {
            myScope.async { viewModelService.findVersionUpdate() }.await()
        }
    }


    private fun parseFindVersionUpdateResult(data: DataResult<BaseYgxRsp>) {
        data.onSuccess {
            onBizOK<VersionListBean> { code, data, message, result ->
                if ((data?.size ?: 0) > 0) {
                    val mVersionListBean = data?.get(0)
                    checkUpVersion(mVersionListBean)
                }
            }
            onBizError<Any> { code, message, data ->
                showToast(message)
            }
        }
    }

    private suspend fun checkTokenSuspend(): DataResult<BaseYgxRsp> {
        return withContext(Dispatchers.IO) {
            myScope.async { viewModel.refreshtoken() }.await()
        }
    }

    private fun parseTokenResult(data: DataResult<BaseYgxRsp>) {
        data.onSuccess {
            onBizOK<TokenBean> { code, data, message, result ->
                if (data != null && !TextUtils.isEmpty(data.token)) {
                    YgxUtilsKt.setAppToken(data.token, data.refreshtoken)
                    latestUser()


                } else {
                    logOut()
                }
            }
            onBizError<TokenBean> { code, message, data ->
//                showToast(message)
                logOut()

            }
        }
    }

    private fun checkUpVersion(mVersionListBean: VersionUpdate?) {
//        loadFinished()
        val isprivacy = mVersionListBean?.isprivacy//是否显示隐私弹窗
        val fristLoadVersion =
            SPStaticUtils.getString(Constants.ISFRISTLOADVERSION, "")
        if (!fristLoadVersion.isNullOrEmpty() && fristLoadVersion != isprivacy) {
            showFirstDialog(isprivacy ?: "", mVersionListBean)
        } else {
            SPStaticUtils.put(Constants.ISFRISTLOADVERSION, isprivacy ?: "")
            checkUpDataVersion(mVersionListBean)
        }
    }

    private fun showFirstDialog(
        isprivacy: String,
        versionListBean: VersionUpdate?
    ) {
        val firstDialog: FirstDialog = FirstDialog(this@HomeActivity)
        firstDialog.setCanceledOnTouchOutside(false)
        firstDialog.show()
        firstDialog.setLeftBtnClickListener {
            firstDialog.dismiss()
            ActivityUtils.finishAllActivities()
        }
        firstDialog.setRightBtnClickListener {
            SPStaticUtils.put(Constants.ISFRISTLOADVERSION, isprivacy)
            firstDialog.dismiss()
            checkUpDataVersion(versionListBean)
        }
    }

    override fun initData() {
        super.initData()
//        mBinding.homeBottomTab.setTabGone(3)
        doWorkManager()
        UserDbHelper.getLiveUserInfo(this).observeKt { userInfo ->
            if (userInfo != null && !userInfo.id.isNullOrEmpty()) {
//                YgxApplication.getInstance().registerPushManually()
                sendIMToken(userInfo.phone)
            }
        }
    }

    private fun sendIMToken(phone: String?) {
        val userphone = phone ?: ""
        val token = SPUtils.getInstance().getString("im_register", "")
        val appVersionCode = AppUtils.getAppVersionName()
        val brand = DeviceUtils.getManufacturer()
        LogUtils.e("aaa")
        lifecycleScope.launchWhenCreated {
            val imMap = mutableMapOf<String, String>(
                "phone" to userphone,
                "plat" to brand,
                "sion" to appVersionCode,
                "code" to "2",
                "ptoken" to token,
            )
            val result: DataResult<BaseYgxRsp> =
                myScope.async { viewModel.saveTX(imMap) }.await()
        }
    }

    /**
     * 执行后台任务
     */
    private fun doWorkManager() {
        YgxToolsKt.doWorkManager(this)
    }

    override fun initConfig() {
        super.initConfig()
        registerComponentCallbacks(MemoryCallBack(this@HomeActivity))

        LogUtil.e("HomeActivity======Opencount====", "openCount")
        loadUI()

        UserDbHelper.getLiveUserInfo(this@HomeActivity).observeKt {
            mUserInfo = it
            viewModel.liveUser.value = it
            val isHasLogin = !it?.id.isNullOrEmpty()
            if (!isLogin && isHasLogin && it?.id != mUserId) {//登录
                uiConvList.clear()
                mUserTxaccid = it?.txaccid ?: ""
                mUserId = it?.id ?: ""
                isLogin = true
                val phone = it?.phone
                SPStaticUtils.put("userPhone", phone)
                initUnreadCount()
                YgxApplication.getInstance().registerPushManually()
                YgxUtilsKt.sendMessgeToSelf(it?.txaccid, it?.phone)
                sendIMToken(it?.phone)
            } else {//未登录
                isLogin = false
                mUserId = ""
                mBinding.homeBottomTab.setMessageCount("0")
                mBinding.homeBottomTabNew.setMessageCount("0")
                setUnReadCirCount(0)
                setUnReadMessageCount(0)
                upDataAppUnreadCounts(0)
            }
        }

        getIntentData(intent)
    }

    override fun initEvents() {
        super.initEvents()
        rigestEventBus()
    }

    private fun rigestEventBus() {
        LiveEventBus.get(MessageCountEvent::class.java).observe(this) {
            if (it == null) {
                return@observe
            }
            val filter = V2TIMConversationListFilter()
            filter.hasUnreadCount = true
            V2TIMManager.getConversationManager().getConversationListByFilter(
                filter,
                0,
                50,
                object : V2TIMValueCallback<V2TIMConversationResult?> {
                    override fun onSuccess(v2TIMConversationResult: V2TIMConversationResult?) {
                        // 获取会话列表成功
                        val conversationList = v2TIMConversationResult?.conversationList
                        conversationList?.let {
                            uiConvList.clear()
                            uiConvList.addAll(conversationList)
                            getUnreadCount(uiConvList)
                        }
                    }

                    override fun onError(code: Int, desc: String) {
                        // 获取会话列表失败
                    }
                })
        }
        LiveEventBus.get(LocationEvent::class.java).observe(this) { s ->
            if (s == null) {
                return@observe
            }
            if (s.state) {
                checkPermissionLoction()
            }
        }
        LiveEventBus.get(LocationChangeEvent::class.java).observe(this) { event ->
            if (event == null) {
                return@observe
            }
//            if (mCurrentProvince.contains(event.province ?: "") || (event.province ?: "").contains(
//                    mCurrentProvince
//                )
//            ) {
//            } else {
//                mCurrentProvince = event.province ?: ""
//            }
            if (!event.province.isNullOrEmpty()) {
                findADLocationChange()
            }
        }
        LiveEventBus.get(VersionUpdataRefreshEvent::class.java).observe(this) { event ->
            if (event == null) {
                return@observe
            }
            val progress = event.progress
            if (mLoadingDialog?.isShowing == false) {
                mLoadingDialog?.show()
            }
            var hint = ""
            if (progress == 100) {
                hint = "下载完成"
            } else {
                hint = "下载进度:${progress}%"
            }
            mHint?.text = hint
        }
        LiveEventBus.get(HomeTabEvent::class.java).observe(this) { event ->
            if (event == null) {
                return@observe
            }
            mTab = event.tag
            setCurrentTab(mTab)
        }


//        LiveEventBus
//            .get(LiveEventUtils.REFRESH_HOME_ACTIVE_OPEN_KEY, String::class.java)
//            .observe(this) {
//                mBinding.clFloat.visibility = if (it == "0") View.GONE else View.VISIBLE
//            }
    }

    private fun initTabStyle() {
        if (mNewYear == 0) {
            mBinding.homeBottomTab.init(supportFragmentManager, pageViewModel)
            mBinding.homeBottomTab.setOnTabPagerListener(object :
                HomeBottomTabWidget.TabPagerListener {
                override fun OnClickTab(position: Int) {
                    if (position >= 0) {
                        if ((position == 2 || position == 3) && (mUserInfo == null || mUserInfo?.id.isNullOrEmpty())) {
                            pageViewModel.setPage(BOTTOM_TAB_POSITION)
                            mBinding.homeBottomTab.init(
                                supportFragmentManager,
                                pageViewModel
                            )
                            LiveEventBus.get(VideoPlayEvent::class.java)
                                .post(VideoPlayEvent("", PlayStatus.STOP))
                            ARouter.getInstance().build(ARoutUtils.OneKeyLoginActivityURL)
                                .navigation()
                        } else {
                            BOTTOM_TAB_POSITION = position
                            LiveEventBus.get(VideoPlayEvent::class.java)
                                .post(VideoPlayEvent("", PlayStatus.PLAY))
                        }
                        mBinding.homeBottomTab.setTabStyle(BOTTOM_TAB_POSITION)
                        initToolBar(BOTTOM_TAB_POSITION)
                    } else if (position == -1) {
                        LiveEventBus.get(RefreshPageEvent::class.java)
                            .post(RefreshPageEvent("HomeActivity", -1))
                    }
                }
            })
        } else {
            mBinding.homeBottomTab.visibility = View.GONE
            mBinding.homeBottomTabNew.visibility = View.VISIBLE
            mBinding.homeBottomTabNew.init(supportFragmentManager, pageViewModel)
            mBinding.homeBottomTabNew.setOnTabPagerListener(object :
                HomeBottomTabNewWidget.TabPagerListener {
                override fun OnClickTab(position: Int) {
                    if (position >= 0) {
                        if ((position == 2 || position == 3) && (mUserInfo == null || mUserInfo?.id.isNullOrEmpty())) {
                            pageViewModel.setPage(BOTTOM_TAB_POSITION)
                            mBinding.homeBottomTabNew.init(
                                supportFragmentManager,
                                pageViewModel
                            )
                            LiveEventBus.get(VideoPlayEvent::class.java)
                                .post(VideoPlayEvent("", PlayStatus.STOP))
                            ARouter.getInstance().build(ARoutUtils.OneKeyLoginActivityURL)
                                .navigation()
                        } else {
                            BOTTOM_TAB_POSITION = position
                            LiveEventBus.get(VideoPlayEvent::class.java)
                                .post(VideoPlayEvent("", PlayStatus.PLAY))
                        }
                        mBinding.homeBottomTabNew.setTabStyle(BOTTOM_TAB_POSITION)
                        initToolBar(BOTTOM_TAB_POSITION)
                    } else if (position == -1) {
                        LiveEventBus.get(RefreshPageEvent::class.java)
                            .post(RefreshPageEvent("HomeActivity", -1))
                    }
                }
            })
        }
    }

    private fun checkPermissionLoction() {
        val loctiontPermissCoarse =
            PermissionXUtils.hasPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
        val loctiontPermissFine =
            PermissionXUtils.hasPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
        val permissions = mutableListOf<String>()
        if (!loctiontPermissCoarse) {
            permissions.add(Manifest.permission.ACCESS_COARSE_LOCATION)
        }
        if (!loctiontPermissFine) {
            permissions.add(Manifest.permission.ACCESS_FINE_LOCATION)
        }
        if (permissions.isNotEmpty()) {
            initStatusBar(this, true, true)
            mBinding.clTopLocation.visibility = View.VISIBLE
            // 用于在您浏览、搜索或参与特定活动时，向您展示当前城市服务信息，以提升体验。不申请该权限不影响APP的正常使用。是否同意去申请该权限？
            PermissionXUtils.checkPermissBefore(
                this,
                permissions,
                "是否同意授予位置权限用于当前页面展示当前城市的服务信息，以提升体验。不申请该权限不影响APP的正常使用。",
                object : PermissionXUtilsCallback {
                    override fun permissionCallback(
                        allGranted: Boolean,
                        grantedList: List<String?>,
                        deniedList: List<String?>,
                    ) {
                        if (allGranted) {
                            mBinding.clTopLocation.visibility = View.GONE
                            startLocation()
                        } else {
                            initStatusBar(this@HomeActivity, true, false)
                            mBinding.clTopLocation.visibility = View.GONE
                        }
                    }

                    //用户点击了禁止
                    override fun fotPermsission() {
                        initStatusBar(this@HomeActivity, true, false)
                        mBinding.clTopLocation.visibility = View.GONE

                    }
                },
            )
        } else {
            startLocation()
        }


    }

    private var mADBean: VersionUpdate? = null

    private fun findADLocationChange() {//全屏广告
//        lifecycleScope.launch {
//            val mapBanner = mapOf<String, String>(
//                "province" to SPStaticUtils.getString(Constants.SP_KEY_ADDRESS_PROVINCE),
//                "code" to "8"
//            )
//            val result: DataResult<BaseYgxRsp> =
//                myScope.async { viewModelService.findAllBanner(mapBanner) }.await()
//            parseADChangeResult(result)
//        }
    }

    private fun parseADChangeResult(data: DataResult<BaseYgxRsp>) {
        data.onSuccess {
            onBizOK<VersionListBean> { code, data, message, result ->
                if (!data.isNullOrEmpty()) {
                    mADBean = data[0]
                    showAdDialog(mADBean)
                }

            }
            onBizError<Any> { code, message, data ->
                showToast(message)
            }
        }
    }


    /**
     * 全屏广告
     */
    private var mADDialog: VersionUpdateDialog? = null
    private fun showAdDialog(versionListBean: VersionUpdate?) {
        if (versionListBean == null) {
            return
        }
        mADDialog =
            VersionUpdateDialog(
                this@HomeActivity,
                versionListBean,
                versionListBean.iscompel != "1",
                versionListBean.iscompel != "1",
                object : OnDialogListener {
                    override fun onSureClick(content: String?) {
                        val tag = versionListBean.tag
                        YgxAroutPageKt.arout2page(
                            this@HomeActivity,
                            tag, versionListBean.url, mUserInfo, adId = versionListBean.id ?: -1
                        )
                    }

                    override fun onCancelClick() {
                    }
                })
        mADDialog?.show()
//        owner.join(ADDialog)
    }

    private fun startLocation() {
        val isOPen = YgxUtilsKt.isOPen(this)

        if (isOPen) {

            LocationUtils.getInstance().getLocations(this@HomeActivity)

            var province = SPStaticUtils.getString(Constants.ADDRESS_PROVINCE_KEY)
            var city = SPStaticUtils.getString(Constants.ADDRESS_CITY_KEY)
            var area = SPStaticUtils.getString(Constants.ADDRESS_AREA_KEY)
            var time = SPStaticUtils.getLong(Constants.LOCATION_TIME_KEY, 0)
            val locationLat = SPStaticUtils.getString(Constants.LOCATION_LAT_KEY) //保存定位的径度
            val locationLon = SPStaticUtils.getString(Constants.LOCATION_LNG_KEY) //保存定位的纬度
            var forshort = ""
            if (province.isEmpty()) {
                forshort = addressDefult.forshort ?: ""
                province = addressDefult.province
                city = addressDefult.city
                area = addressDefult.area
                time = System.currentTimeMillis()
            }
            if (city != null && city.isNotEmpty() && city.endsWith("市")) {
                city = city.dropLast(1)
            }
            lifecycleScope.launch {
                val address = AddressCurrentDbHelper.getAddress(this@HomeActivity)
                if (address == null || TextUtils.isEmpty(address.province)) {//没有定位过
                    saveLoction(forshort, province, city, area, locationLat, locationLon)
                    //检查首页全屏弹窗
//                    runOnUiThread {
//                        showALLDialog()
//                    }
                } else {
                    val disanceTime = System.currentTimeMillis() - time
                    var forshortLoaction = address.forshort

                    if (!(address.province!!.contains(province) || province.contains(address.province!!)) && disanceTime > LOCATION_TIME && !loadAddress) {
                        if (forshortLoaction.isNullOrEmpty()) {
                            val firstLoaction =
                                mAddressBeans.firstOrNull {
                                    it.name.contains(province) || province.contains(
                                        it.name
                                    )
                                }
                            if (firstLoaction != null) {
                                forshortLoaction = firstLoaction.forshort
                            }
                        }
                        locationPosition(
                            forshortLoaction, province, city, area, locationLat, locationLon
                        )
                    } else {
                        if (forshortLoaction.isNullOrEmpty()) {
                            val firstLoaction =
                                mAddressBeans.firstOrNull {
                                    it.name.contains(province) || province.contains(
                                        it.name
                                    )
                                }
                            if (firstLoaction != null) {
                                forshortLoaction = firstLoaction.forshort
                            }
                            SPStaticUtils.put(
                                Constants.SP_KEY_ADDRESS_PROVINCE_FORSHORT,
                                forshortLoaction
                            )

//                            saveLoction(
//                                forshortLoaction, province, city, area, locationLat, locationLon
//                            )
                        }
                        //检查首页全屏弹窗
//                        runOnUiThread {
//                            showALLDialog()
//                        }
                    }
                }
            }

        } else {
            //检查首页全屏弹窗
//            showALLDialog()
            setDefaultLocation()
            SPStaticUtils.put(Constants.SP_KEY_ADDRESS_PROVINCE_FORSHORT, addressDefult.forshort)
            SPStaticUtils.put(Constants.ADDRESS_PROVINCE_KEY, addressDefult.province)
            SPStaticUtils.put(Constants.ADDRESS_CITY_KEY, addressDefult.city)
            SPStaticUtils.put(Constants.ADDRESS_AREA_KEY, addressDefult.area)
        }

    }

    private fun setDefaultLocation() {
        MainScope().launch {
            val address = AddressCurrentDbHelper.getAddress(this@HomeActivity)
            if (address == null || TextUtils.isEmpty(address.province)) {
                saveLoction(
                    addressDefult.forshort,
                    addressDefult.province,
                    addressDefult.city,
                    addressDefult.area,
                    addressDefult.latitude,
                    addressDefult.longitude
                )
            }
        }
    }

    private fun locationPosition(
        forshort: String?,
        province: String?,
        city: String?,
        area: String?,
        locationLat: String?,
        locationLon: String?
    ) {
        loadAddress = true
//        runOnUiThread {
//        MainScope().launch {
        mLocationDialog = TipsCancel2Dialog(
            this@HomeActivity,
            "当前位置发生变化",
            false,
            false,
            object : OnDialogListener {
                override fun onSureClick(content: String?) {
                    //检查首页全屏弹窗
                    if (mADDialog?.isShowing == true) {
                        mADDialog?.dismiss()
                    }
                    CoroutineScope(Dispatchers.IO).launch {
                        saveLoction(forshort, province, city, area, locationLat, locationLon)
                    }
//                    showALLDialog()
                }

                override fun onCancelClick() {
                    SPStaticUtils.put(
                        Constants.LOCATION_TIME_KEY,
                        System.currentTimeMillis()
                    )//设置定位的更新时间
                    //检查首页全屏弹窗
//                    showALLDialog()
                }
            }
        )
        mLocationDialog?.show()
    }

    /**
     * 保存定位
     */
    private fun saveLoction(
        forshort: String?,
        province: String?,
        city: String?,
        area: String?,
        locationLat: String?,
        locationLon: String?
    ) {
//        mCurrentProvince = province ?: ""
        SPStaticUtils.put(Constants.SP_KEY_ADDRESS_PROVINCE_FORSHORT, forshort)
        SPStaticUtils.put(Constants.SP_KEY_ADDRESS_PROVINCE, province)
        SPStaticUtils.put(Constants.SP_KEY_ADDRESS_CITY, city)
        SPStaticUtils.put(Constants.SP_KEY_ADDRESS_AREA, area)
        SPStaticUtils.put(Constants.SP_KEY_ADDRESS_TIME, System.currentTimeMillis()) //最后一次成功获取定位的时间
//        SPStaticUtils.put(Constants.LOCATION_TIME_KEY, System.currentTimeMillis()) //保存上次定位时间的key
        SPStaticUtils.put(Constants.SP_KEY_ADDRESS_LAT, locationLat) //保存定位的径度
        SPStaticUtils.put(Constants.SP_KEY_ADDRESS_LON, locationLon) //保存定位的纬度
        AddressCurrentDbHelper.insertAddress(
            this@HomeActivity,
            CurrentAddress(
                0, forshort, province, city,
                area, System.currentTimeMillis(), locationLat, locationLon
            )
        )

    }


    private fun latestUser() {
        lifecycleScope.launchWhenCreated {
            val result: DataResult<BaseYgxRsp> =
                myScope.async { viewModelService.latestUser() }.await()
            parseLastUserResult(result)
        }

    }

    private fun parseLastUserResult(data: DataResult<BaseYgxRsp>) {
        data.onSuccess {
            onBizOK<UserInfo> { code, data, message, result ->
                if (data == null) {
                    logOut()
                } else {
                    YgxApplication.getInstance().init(GenerateTestUserSig.SDKAPPID)
                    login(data)
                    UserDbHelper.UpDataUserInfo(this@HomeActivity, data)
                }
            }
            onBizError<TokenBean> { code, message, data ->
//                showToast(message)
                logOut()

            }
        }
    }

    private fun login(userInfo: UserInfo) {
        TUILogin.login(
            this,
            YgxApplication.getInstance().getSdkAppId(),
            userInfo.txaccid,
            userInfo.txaccidpassword,
            object :
                TUICallback() {
                override fun onSuccess() {
                    isLogin = true
                    initUnreadCount()
                    YgxUtilsKt.sendMessgeToSelf(userInfo.txaccid, userInfo.phone)
                }

                override fun onError(errorCode: Int, errorMessage: String?) {
                    showToast("登录失败 $errorCode,errorInfo = $errorMessage")
//                    startLogin()
                    UserDbHelper.deleteUserInfo(this@HomeActivity)
                }
            })
    }


    //检查更新弹窗
    private fun checkUpDataVersion(versionListBean: VersionUpdate?) {
        val location = YgxUtilsKt.checkLocationPermission(this@HomeActivity)
        if (versionListBean == null) {
            locationInit(location)
            return
        }
        val versionID = versionListBean.jump
        val status = versionListBean.iscompel ?: "0" //1 一直显示
//        val versionID = "2.5.0"
//        val status = "0"
        downUrl = versionListBean.url ?: ""
        val compareVersion =
            MyUtils.compareVersion(
                BaseApplication._versionName,
                versionID
            )//0代表相等，1代表systemVersion大于android_version_num，-1代表systemVersion小于android_version_num
        if (compareVersion == -1) {//版本更新 // 版本号不同 当前版本大于强制更新版本，不升级，小于，升级
            upDataDialog =
                VersionUpdateDialog(
                    this@HomeActivity,
                    versionListBean, status != "1", status != "1", object : OnDialogListener {
                        override fun onSureClick(content: String?) {
                            val appName = AppUtils.getAppVersionName()
                            val manager = DownloadManager.Builder(this@HomeActivity).run {
                                apkUrl(downUrl)
                                apkName("suyiyiong.apk")
                                smallIcon(com.lv.common.R.drawable.ic_logo)
                                //设置了此参数，那么内部会自动判断是否需要显示更新对话框，否则需要自己判断是否需要更新
//                                apkVersionCode(2)
                                //同时下面三个参数也必须要设置
                                apkVersionName(appName)
//                                apkSize("7.7MB")
//                                apkDescription("更新描述信息(取服务端返回数据)")
                                onDownloadListener(object : OnDownloadListener {
                                    override fun cancel() {
                                    }

                                    override fun done(apk: File) {
                                        val hint = "下载完成"
                                        mHint?.text = hint
                                        if (packageManager.canRequestPackageInstalls()) {
                                            if (!downUrl.isNullOrEmpty()) {
                                                updataLoading()
                                                val intent =
                                                    Intent(
                                                        this@HomeActivity,
                                                        UpdataAppService::class.java
                                                    )
                                                intent.putExtra("url", downUrl)
                                                startService(intent)
                                                return
                                            }
                                        } else {
                                            upDataDialog.show()
                                        }
                                    }

                                    override fun downloading(max: Int, progress: Int) {
//                                        val progress = event.progress
                                        if (mLoadingDialog?.isShowing == false) {
                                            mLoadingDialog?.show()
                                        }
                                        val process = ((progress.toFloat() / max) * 100).toInt()
                                        val hint = "下载进度:${process}%"
                                        mHint?.text = hint
                                    }

                                    override fun error(e: Throwable) {
                                    }

                                    override fun start() {
                                        updataLoading()
                                    }
                                })
                                //省略一些非必须参数...
                                build()

                            }
                            manager.download()

                        }

                        override fun onCancelClick() {
//                            if (status == "1") {
//                                ActivityCollector.finishAll()
//                            } else {
//                                locationInit(location)
////                                checkPermissionLoction()
//                                upDataDialog.dismiss()
//                            }
                            upDataDialog.dismiss()
                            //                                        registerCutAndCopyEvents()
                        }
                    })
            upDataDialog.show()
        } else {
            locationInit(location)
//            checkPermissionLoction()
        }
    }

    //判断是否定位
    private fun locationInit(location: Boolean) {
        if (location) {
            startLocation()
        } else {
//            showALLDialog()
            setDefaultLocation()
        }
    }

    private fun logOut() {
        TUILogin.logout(object : TUICallback() {
            override fun onSuccess() {
                V2TIMManager.getConversationManager()
                    .removeConversationListener(null)
            }

            override fun onError(errorCode: Int, errorMessage: String?) {
            }
        })
        //清除Token
        YgxUtilsKt.setAppToken("", "", "")
        UserDbHelper.deleteUserInfo(this@HomeActivity)
        OfflineMessageDispatcher.updateBadge(this@HomeActivity, 0)

    }

    private val MAX_VALUE = 50

    private fun initUnreadCount() {
//        uiConvList.clear()
        V2TIMManager.getConversationManager()
            .addConversationListener(v2TIMConversationListener)
        // 2. 先拉取50个本地会话做 UI 展示，nextSeq 第一次拉取传0
        V2TIMManager.getConversationManager().getConversationList(
            0, MAX_VALUE,
            object : V2TIMValueCallback<V2TIMConversationResult?> {
                override fun onSuccess(v2TIMConversationResult: V2TIMConversationResult?) {
                    val nextSeq = v2TIMConversationResult?.nextSeq
                    LogUtils.e(
                        "imsdk",
                        "success nextSeq:" + nextSeq + ", isFinish:" + v2TIMConversationResult?.isFinished
                    )
                    val v2TIMConversationList = v2TIMConversationResult?.conversationList
                    v2TIMConversationList?.let {
                        updateConversation(it)
                    }
                    val conList = v2TIMConversationResult!!.conversationList
                    // 拉取成功，更新 UI 会话列表
                    updateConversation(conList)
                    if (!v2TIMConversationResult.isFinished) {
                        V2TIMManager.getConversationManager().getConversationList(
                            v2TIMConversationResult.nextSeq, MAX_VALUE,
                            object : V2TIMValueCallback<V2TIMConversationResult?> {
                                override fun onError(code: Int, desc: String) {
                                    LogUtil.e("messageFragment", "onError")
                                }

                                override fun onSuccess(v2TIMConversationResult: V2TIMConversationResult?) {
                                    LogUtil.e("messageFragment", "onSuccess")

                                    // 拉取成功，更新 UI 会话列表
                                    v2TIMConversationResult?.let {
                                        updateConversation(
                                            it.conversationList,
                                        )
                                    }
                                }
                            })
                    }
                }

                override fun onError(code: Int, desc: String) {
                    LogUtils.e("imsdk", "failure, code:$code, desc:$desc")
                }
            })
    }

    private fun setUnReadMessageCount(unreadCount: Int) {
        var unreadStr = "" + unreadCount
        if (unreadCount > 100) {
            unreadStr = "99 +"
        }
        mBinding.homeBottomTab.setMessageCount(unreadStr)
        mBinding.homeBottomTabNew.setMessageCount(unreadStr)
    }

    private fun setUnReadCirCount(unreadCount: Int) {
        var unreadStr = "" + unreadCount
        if (unreadCount > 100) {
            unreadStr = "99 +"
        }
        mBinding.homeBottomTab.setCartCount(unreadStr)
        mBinding.homeBottomTabNew.setCartCount(unreadStr)
        LiveEventBus.get(MessageCirCountEvent::class.java)
            .post(MessageCirCountEvent(unreadCount))
    }

    private fun upDataAppUnreadCounts(unreadCountTotal: Int) {
        // update Huawei offline push Badge
        OfflineMessageDispatcher.updateBadge(this@HomeActivity, unreadCountTotal)

    }

    private fun setCurrentTab(tabId: Int) {
        if (BOTTOM_TAB_POSITION == tabId) {
            return
        }
        try {
            pageViewModel.setPage(tabId)
            if (mNewYear == 0) {
                mBinding.homeBottomTab.init(supportFragmentManager, pageViewModel)
                mBinding.homeBottomTab.setTabStyle(BOTTOM_TAB_POSITION)
            } else {
                mBinding.homeBottomTabNew.init(supportFragmentManager, pageViewModel)
            }
            BOTTOM_TAB_POSITION = tabId
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        setIntent(intent)
        getIntentData(intent)
    }

    private fun getIntentData(intent: Intent?) {
        LogUtils.e("外部：${URLDecoder.decode(intent?.data.toString())}")
        if (intent?.extras != null) {
            val action = intent.action
            if (Intent.ACTION_VIEW == action) {
                val uri: Uri? = intent.data
                if (uri != null) {
                    var result = uri.toString()
                    result = URLDecoder.decode(result)
                    val scanCode = "type=3&newsId=&subType=1"
                    if (result.contains(scanCode)) {
                        val split = result.split("genre=").toTypedArray()
                        val s = split[1]
                        val jsonType = object : TypeToken<ScanCodeBean?>() {}.type
                        val jt: ScanCodeBean = GsonUtils.fromJson(s, jsonType)
                        val contentId: String = jt.contentId ?: ""
//                        ARouter.getInstance().build(ARoutUtils.CompanyInfoActivity)
//                            .withString("cpyid", contentId)
//                            .withString("subType", "1").navigation()
                        return
                    }
                    /* if (result.contains(Constants.KEY_SHARE_COMPANY_CASH)) {
                         //https://www.suyiyong.cn/timeNeed/ceshi/#/shopIndex?d=2&tt=0&h=0&t=4&ti=13367276910
                         val s = result.split("shopIndex?")[1]
                         if (s.contains("&")) {
                             val split = s.split("&")
                             for (item in split) {
                                 if (item.contains("ti") || item.contains("state")) {
                                     val contentId = item.split("=")[1]
                                     ARouter.getInstance().build(ARoutUtils.CompanyInfoActivity)
                                         .withString("cpyid", contentId)
                                         .withString("subType", "1").navigation()
                                     break
                                 }
                             }
                         }

                         LogUtils.e(s)
 //
                         return
                     }
                     //新码
                     if (result.contains("openwith")) {
                         loadURLPage(result)
                     }*/
                }
            }


//            val spuId = intent.getStringExtra("spuId") //商家端上架列表商品Item点击进来
//            if (!TextUtils.isEmpty(spuId)) {
//                UiHelp.showShopDeDetailActivity(this@HomeActivity, spuId)
//            }
            mTab = intent.getIntExtra("tabId", 0) //主页tab
            setCurrentTab(mTab)
        }
    }

    override fun onResume() {
        super.onResume()
        LogUtils.e("onResume")
//        initStatusBar(this, true, pageViewModel.getPage() != 1)
        val page = pageViewModel.getPage() ?: 0
        initToolBar(page)
//        val nullOrEmpty = mUserInfo?.id.isNullOrEmpty()
//        if (pageViewModel.getPage() == 2 && nullOrEmpty) {
//            setCurrentTab(0)
//        }
    }

    private fun loginPc(sessionId: String) {
//        lifecycleScope.launchWhenCreated {
//            val result: DataResult<BaseYgxRsp> =
//                myScope.async { viewModelService.mobileOkPcLogin(LoginReqByScanBody(sessionId)) }
//                    .await()
//            parseLoginPcResult(result)
//        }
    }

    private fun parseLoginPcResult(data: DataResult<BaseYgxRsp>) {
        data.onSuccess {
            onBizOK<Any> { code, data, message, result ->
                if (message != null) {
                    showToast(message)
                }
            }
            onBizError<String> { code, message, data ->
                showToast(message)
                ARouter.getInstance().build(ARoutUtils.OneKeyLoginActivityURL).navigation()

            }
        }
    }

    private fun loadURLPage(result: String?) {
        LogUtils.e("外部url:$result")
        val map = YgxUtilsKt.urlParmasToMap(url = result)
        val state = map["state"].toString()
        if (state.isNotEmpty() && state != "null") {
//            ARouter.getInstance().build(ARoutUtils.CompanyInfoActivity)
//                .withString("cpyid", state)
//                .withString("subType", "0")
//                .withBoolean("showAD", true).navigation()
        } else {
            val t = map["t"]
            val id = map["ti"].toString()
            when (t) {
                "0" -> {//入驻亨富然


//                    ARouter.getInstance().build(ARoutUtils.CardPageActivity)
//                        .withString("cpyid", id).navigation()
                }

                "1" -> {//App内
                    ARouter.getInstance().build(ARoutUtils.WebActivity)
                        .withString("url", id).navigation()
                }

                "2" -> {//App内
                    val uri = Uri.parse(id)
                    val intent = Intent(Intent.ACTION_VIEW, uri)
                    startActivity(intent)
                }


            }
        }

    }


    private val v2TIMConversationListener: V2TIMConversationListener =
        object : V2TIMConversationListener() {
            // 3.1 收话新增的回调
            @RequiresApi(api = Build.VERSION_CODES.N)
            override fun onNewConversation(conversationList: List<V2TIMConversation>) {
                super.onNewConversation(conversationList)
                LogUtil.e("onNewConversation", "onNewConversation")
                updateConversation(conversationList)

            }

            // 3.2 收到会话更新的回调
            @RequiresApi(api = Build.VERSION_CODES.N)
            override fun onConversationChanged(conversationList: List<V2TIMConversation>) {
                if (conversationList.isEmpty()) {
                    return
                }
                updateConversation(conversationList)

            }

        }

    private fun updateConversation(convList: List<V2TIMConversation>) {
        if (convList.isEmpty()) {
            return
        }

        for (i in convList.indices) {
            val conv = convList[i]
            var isExit = false
            for (j in uiConvList.indices) {
                val uiConv = uiConvList[j]
                // UI 会话列表存在该会话，则替换
                if (uiConv.conversationID == conv.conversationID) {
                    uiConvList[j] = conv
                    isExit = true
                    break
                }
            }
            // UI 会话列表没有该会话，则新增
            if (!isExit) {
                uiConvList.add(conv)
            }
        }
        analysisMessage()
        val v2TIMConversation = convList[0]
        checkLoginOtherDevice(v2TIMConversation)
    }

    private fun analysisMessage() {
        getUnreadCount(uiConvList)

    }

    private fun getUnreadCount(conversationList: MutableList<V2TIMConversation>) {
        var unreadCount = 0
        var unreadCir = 0
        conversationList.let {
            conversationList.forEach { conversationItem ->
                val conversation: ConversationInfo =
                    ConversationUtils.convertV2TIMConversation(conversationItem)
                var conversationID = conversationItem.conversationID
                if (conversationID.startsWith("c2c_")) {
                    conversationID = conversationID.drop(4)
                }
//                if (conversationID == Constants.ID_HQ) {
//                    unreadCir = conversationItem.unreadCount
//                } else {
//                    val unread = conversationItem.unreadCount
//                    if (!conversation.isShowDisturbIcon) {
//                        if (unread > 0) {
//                            unreadCount += unread
//                        } else {
//                            val markUnread = conversation.isMarkUnread
//                            if (markUnread) {
//                                unreadCount++
//                            }
//                        }
//                    }
//                }

            }
        }
        mCirNum = unreadCir
        mMessageNum = unreadCount
        setUnReadCirCount(mCirNum)
        setUnReadMessageCount(mMessageNum)
        val totleCount = mCirNum + mMessageNum
        upDataAppUnreadCounts(totleCount)
    }


    private fun checkLoginOtherDevice(v2TIMConversation: V2TIMConversation) {
        val chatTag = SPStaticUtils.getString(Constants.KEY_CHAT_TOKEN, "aaa")
        val userID = v2TIMConversation.userID
//        if (userID.startsWith("c2c_")) {
//            userID = userID.drop(4)
//        }
        if (mUserInfo?.txaccid == userID) {
            if (v2TIMConversation.lastMessage == null) {
                return
            }
            val customText = v2TIMConversation.lastMessage.customElem
            val dataCustom = customText ?: return
            val customJson = dataCustom.data.toString(Charsets.UTF_8)
            val jsonType = object : TypeToken<CustomMessageBean?>() {}.type
            val jt: CustomMessageBean = GsonUtils.fromJson(customJson, jsonType)
            val idSyyAccid = jt.id_syy_accid
            if (!idSyyAccid.contains("亨富然")) {
                return
            }
            val split = idSyyAccid.split("亨富然".toRegex()).toTypedArray()
            if (split.size < 3) {
                return
            }
            if (mUserInfo?.txaccid != split[1]) {
                return
            }
            if (mUserInfo?.phone != split[2]) {
                return
            }
            if (!TextUtils.isEmpty(chatTag) && chatTag != "aaa" && split[0] != chatTag) {
                TUILogin.logout(object : TUICallback() {
                    override fun onSuccess() {
                        YgxUtilsKt.setAppToken("", "", "")
                        V2TIMManager.getConversationManager()
                            .removeConversationListener(null)
                        setCurrentTab(0)
                        ActivityUtils.finishToActivity(
                            HomeActivity::class.java, false
                        )//所有页面出栈
                        ARouter.getInstance().build(ARoutUtils.LoginOutActivity)
                            .navigation()
//                        showLoginOutDialog()
                    }

                    override fun onError(errorCode: Int, errorMessage: String?) {
                    }
                })

            }
        } else {
//                    V2TIMManager.getMessageManager().getC2CHistoryMessageList(
//                        userID,
//                        2,
//                        null,
//                        object : V2TIMValueCallback<List<V2TIMMessage?>?> {
//                            override fun onSuccess(v2TIMMessages: List<V2TIMMessage?>?) {
//                                v2TIMMessages?.let {
//                                    val size = v2TIMMessages.size
//                                    if (size == 1) {
////                                    makeCall(userID)
//                                    } else if (size > 1) {
//                                        val timestamp = v2TIMMessages[0]!!.timestamp * 1000
//                                        val timestamp2 = v2TIMMessages[1]!!.timestamp * 1000
//                                        val sameDay: Boolean =
//                                            TimeUtil.isSameDay(timestamp, timestamp2)
//                                        if (!sameDay) {
////                                            makeCall(userID)
//                                        }
//                                    }
//                                }
//                            }
//
//                            override fun onError(i: Int, s: String) {}
//
//                        })
        }
    }

    private var mLoadingDialog: Dialog? = null
    private var mHint: TextView? = null
    private fun updataLoading() {
        // 创建一个进度条对话框
        mLoadingDialog = Dialog(this)
        val contentView: View = LayoutInflater.from(this)
            .inflate(R.layout.updata_loading, null)
        mHint = contentView.findViewById<TextView>(R.id.tv_text)
        mLoadingDialog?.setContentView(contentView)
        mLoadingDialog?.window?.setGravity(Gravity.CENTER)
        mLoadingDialog?.setCanceledOnTouchOutside(false)
        mLoadingDialog?.show()

    }


    private fun initToolBar(page: Int) {
        if (mNewYear == 1) {
            when (page) {
                3 -> {
                    initStatusBar(this, true, true)
                }

                else -> {
                    initStatusBar(this, true, false)
                }
            }
        } else {
            initStatusBar(this, true, true)
//            when (page) {
//                0, 1, 2 -> {
//                    initStatusBar(this, true, false)
//                }
//
//                else -> {
//                    initStatusBar(this, true, true)
//                }
//            }
        }

    }


    private suspend fun saveAdStatistics() {
        val adSttistics = YgxAroutPageKt.getAdSttistics()
        if (adSttistics.isEmpty()) {
            return
        }
        val body = ADStatisticsReqBody(adSttistics)
        val result: DataResult<BaseYgxRsp> =
            myScope.async { viewModelService.saveAdStatistics(body) }.await()
//                parseAdStatisticsResult(result)
        SPStaticUtils.put(Constants.AD_STATISTICS, "")
    }

    override fun onBackPressed() {
        super.onBackPressed()
        exitProcess(0)
//        moveTaskToBack(true)
    }

    //
    private var exitTime: Long = 0

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit()
            return false
        }
        return super.onKeyDown(keyCode, event)
    }

    private fun exit() {
        if (System.currentTimeMillis() - exitTime > 2000) {
            showToast("再按一次退出程序")
            exitTime = System.currentTimeMillis()
        } else {
            exitProcess(0)
        }
    }

    override fun onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)

    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode != RESULT_OK) {
            return
        }

//        if (requestCode == REQUEST_CODE_APP_INSTALL) {
//            if (packageManager.canRequestPackageInstalls()) {
//                if (!downUrl.isNullOrEmpty()) {
//                    updataLoading()
//                    val intent =
//                        Intent(
//                            this@HomeActivity,
//                            UpdataAppService::class.java
//                        )
//                    intent.putExtra("url", downUrl)
//                    startService(intent)
//                    return
//                }
//            } else {
//                showToast("暂无安装应用权限")
//                upDataDialog.show()
//            }
//
//        }
        if (data == null) {
            return
        }
        if (supportFragmentManager.fragments.size > 0) {
            val fragments = supportFragmentManager.fragments
            for (fragment in fragments) {
                fragment.onActivityResult(requestCode, resultCode, data)
            }
        }

        when (requestCode) {
            Constants.RESPOND_CAPTURE -> {
                //扫一扫
                var result = data.getStringExtra(CodeUtils.RESULT_STRING)
                if (result.isNullOrEmpty()) {
                    return
                }
                result = URLDecoder.decode(result)

            }

            else -> {
                if (data != null) {
                    //QQ回调
                    ShareUtils.get().onQqActivityResult(requestCode, resultCode, data)
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        if (mADDialog?.isShowing == true) {
            mADDialog?.dismiss()
        }
    }
}